package cao.oschina.app;

import android.content.Context;

import java.lang.reflect.Field;

import cao.oschina.bean.User;
import hd.util.StringHelper;
import hd.util.app.BaseConfig;

/**
 * config
 * <p/>
 * Created by Haidy on 15/3/30.
 */
public class Config extends BaseConfig {

    public static final String COOKIES = "cookies";

    private static Context context;

    /**
     * 实例一个config
     *
     * @param context 上下文
     * @return config
     */
    public static Config instanceConfig(Context context) {
        return Config.context == null ? new Config(context, "config") : null;
    }

    /**
     * 构造函数
     *
     * @param context 上下文
     * @param name    name
     */
    private Config(Context context, String name) {
        super(context, name);
    }

    /**
     * 判断是否加载图片
     *
     * @return 是否加载图片
     */
    public boolean isLoadImage() {
        return getBoolean("load_image", true);
    }

    /**
     * 获取email
     *
     * @return email
     */
    public String getEmail() {
        return getString("email", null);
    }

    /**
     * 获用户id
     *
     * @return uid
     */
    public String getUid() {
        return getString("uid", null);
    }

    /**
     * 保存密码
     *
     * @param pwd password
     */
    public void savePwd(String pwd) {
        saveConfig("pwd", StringHelper.encryptInfo(pwd));
    }

    /**
     * 获取密码
     *
     * @return pwd
     */
    public String getPwd() {
        return StringHelper.decryptInfo(getString("pwd", ""));
    }

    /**
     * 获取cookie
     *
     * @return cookies
     */
    public String getCookies() {
        return getString(COOKIES, null);
    }

    /**
     * 获取用户信息
     *
     * @return user
     */
    public User getUserInfo() {
        User user = new User();
        Class clazz = user.getClass();
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
//                System.out.println(field.getName() + ": " + getString(field.getName(), ""));
                field.set(user, getString(field.getName(), null));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
//        System.out.println(user);
        if (user.name == null) {
            return null;
        }
        return user;
    }

    /**
     * 判断是否登录
     *
     * @return 是否登录
     */
    public boolean isLogin() {
        return getEmail() != null && getPwd() != null && getCookies() != null;
    }

}
